<?php

namespace App\Http\Controllers\Console;

use App\Http\Controllers\Controller;
use App\Model\ShopModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Service\RedisService;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;

class AdminController extends Controller
{

    /**
     * 管理员登录
     * @param Request $request
     * @return array
     */
    public function login(Request $request){
        $username=$request->input('username');
        $password=$request->input('password');
        $uinfo=DB::table("admin")->where("username",$username)->where("status",1)->first();
        if(!$uinfo){
            $arr=["code"=>0,"msg"=>"帐号不存在","data"=>array()];
            return $arr;
        }
        $password=md5($password);
        if($password != $uinfo->password){
            $arr=["code"=>0,"msg"=>"密码错误","data"=>array()];
            return $arr;
        }

        if($uinfo){
            $menu_lists = [];
            //获取左侧菜单信息
            $admin_role_id = $uinfo->admin_role_id;
            //查询该用户权限菜单
            $menus_re = DB::select('select admin_menu_id from admin_purview_menu where admin_purview_id in (select admin_purview_id from admin_role_purview where admin_role_id = '.$admin_role_id.')');
            if($menus_re){
                $menus_re = array_column($menus_re, 'admin_menu_id');
                $menu_lists = $this->menu_lists($menus_re);
            }
            //token存储在redis
            $token = \Str::random (64);
            $redis = new RedisService();
            $data  = $redis->add($token,$uinfo);

            if($data['code'] != 200){
                return ['code'=>1002,'msg'=>'登录失败'];
            }
            $data = [];
            $data['token'] = $token;
            $data['menu_lists'] = $menu_lists;

            return ['code'=>200,'msg'=>'登录成功','data'=>$data];

        }else{
            return ["code"=>0,"msg"=>"登录失败","data"=>array()];
        }

    }

    /**管理员退出
     * @param Request $request
     */
    public function login_out(Request $request){


    }

    /**修改管理员状态 参数：id
     * @param Request $request
     * @return array
     */
    public function change_status(Request $request){

        $id=$request->input("id");
        if($id==""){
            $arr=["code"=>0,"msg"=>"id不能为空"];
            return $arr;
        }
        //查询状态
        $status = DB::table('admin')->where('id',$id)->select('status')->first();
        if(!$status){
            $arr=["code"=>0,"msg"=>"操作失败，请检查数据格式是否正确"];
            return $arr;
        };

        $data = [];
        switch ($status->status){
            case 1: $data['status'] = -1;break;
            case -1: $data['status'] = 1;break;
            default: return ["code"=>0,"msg"=>"操作失败"];
        }

        $re=DB::table('admin')->where("id",$id)->update($data);
        if($re>0){
            $arr=["code"=>200,"msg"=>"操作成功"];
        } else
            $arr=["code"=>0,"msg"=>"操作失败"];

        return $arr;

    }

    /**修改管理员状态 参数：id
     * @param Request $request
     * @return array
     */
    public function del_admin(Request $request){

        $id=$request->input("id");
        if($id==""){
            $arr=["code"=>0,"msg"=>"id不能为空"];
            return $arr;
        }
        //查询状态
        $status = DB::table('admin')->where('id',$id)->select('status')->first();
        if(!$status){
            $arr=["code"=>0,"msg"=>"操作失败，请检查数据格式是否正确"];
            return $arr;
        };

        $data = ['status' => -2];
        $re=DB::table('admin')->where("id",$id)->update($data);
        if($re>0){
            $arr=["code"=>200,"msg"=>"操作成功"];
        } else
            $arr=["code"=>0,"msg"=>"操作失败"];

        return $arr;

    }

    /**
     *注册或编辑管理员
        id: 记录id，传递为修改，不传为增加。
        username:帐号名称
        true_name: 真实姓名
        admin_role_id:角色id
        password:密码,默认为123456
        mobile:联系电话
        type：账号类型：1超级管理员，2普通员工  默认是为1
        status:状态；1：正常，-1：冻结，-2：删除 默认1
     * @param Request $request
     * @return array
     */
    public function register(Request $request){
        $data=array();
        $id=$request->input("id")?$request->input("id"):'';
        $data["admin_role_id"]=$request->input("admin_role_id")?$request->input("admin_role_id"):'';
        $data["username"]=$request->input("username")?$request->input("username"):'';
        $data["password"]=$request->input("password")?$request->input("password"):'';
        $data["type"]=$request->input("type")?$request->input("type"):1;
        $data["status"]=$request->input("status")?$request->input("status"):1;
        $data["true_name"]=$request->input("true_name")?$request->input("true_name"):'';
        $data["mobile"]=$request->input("mobile")?$request->input("mobile"):'';
        $validator=Validator::make($request->input(),[
            'username'  => ['required','max:10','regex:/^[_\w\d\x{4e00}-\x{9fa5}]{3,20}$/iu'],
            'password'  => ['required','min:6','regex:/^[a-zA-Z\d_]{6,}$/'],
            'admin_role_id'  => ['required'],
            'mobile'  => ['regex:/^1[3-8]{1}[0-9]{9}$/'],
        ],[
            'required'=>':attribute为必填项',//:attribute 字段占位符表示字段名称
            'regex'=>':attribute格式不正确',
            'unique'=>':attribute已经存在',
            'max'=>':attribute不能大于10位',
            'min'=>':attribute不能小于6位',
        ],[
            'username'=>'管理员姓名', //指定字段名称
            'password'=>'管理员密码', //指定字段名称
            'admin_role_id'=>'管理员角色', //指定字段名称
            'mobile'=>'联系电话', //指定字段名称
        ]);

        if($validator->fails()){
            return ["code"=>422,"msg"=>$validator->errors()->first()];
        }

        $data["password"] = md5($data["password"]);
        $data["create_at"] = date('Y-m-d H:i:s');

        if($id){
            $re=DB::table('admin')->where("id",$id)->first();
            if(!$re){
                return ["status"=>0,"msg"=>"用户不存在，请刷新再试~"];
            }
            $mid= DB::table("admin")->where("id",$id)->update($data);
        }else{
            $re_user=DB::table("admin")->where("username",$data["username"])->first();
            if($re_user){
                return ["code"=>0,"msg"=>"注册失败，管理员姓名已经存在。"];
            }

            $mid = DB::table("admin")->insertGetId($data);
        }

        if($mid>0)
        {
            $arr=["code"=>200,"msg"=>"操作成功"];
        }else
            $arr=["code"=>0,"msg"=>"操作失败，请检查数据格式是否正确"];

        return $arr;

    }

    /** 获取管理员列表
        参数：id   序号 可选
        return:   admin_role_id   角色id
        username 帐号
        status  1、正常 -1冻结 -2删除（不显示）
        type 账号类型 1普通 2超级管理员
        create_at 创建时间
        true_name  真实姓名
        mobile    联系方式
     * @param Request $request
     * @return array
     */
    public function admin_lists(Request $request){

        $admin = DB::table('admin as a')
            ->leftJoin('admin_role as r','r.id','=','a.admin_role_id')
            ->select('a.id','a.username','r.name as role_name','a.true_name','a.status','a.type','a.mobile','a.create_at')->where('status','!=',-2);

        if($request->input("status") && $request->input("status") >= 0) $admin = $admin->where('a.status','=',$request->input("status"));
        if($request->input("admin_role_id")) $admin = $admin->where('a.admin_role_id','=',$request->input("admin_role_id"));
        if($request->input("username")) $admin = $admin->where('a.username','=',$request->input("username"));

        $admin=$admin->orderBy('id')->paginate(2)->toArray();
        if($admin){
            $arr=["code"=>200,"msg"=>"获取数据成功","data"=>$admin];
        }else
            $arr=["code"=>0,"msg"=>"获取数据失败","data"=>[]];

        return $arr;

    }

    /**
     * 管理员信息详情
     * @param Request $request
     * @return array
     */
    public function admin_details(Request $request){

        $id=$request->input("id");
        if($id==""){
            $arr=["code"=>0,"msg"=>"id不能为空"];
            return $arr;
        }

        $admin_info = DB::table('admin as a')
            ->leftJoin('admin_role as r','r.id','=','a.admin_role_id')
            ->select('a.id','a.username','r.name as role_name','a.true_name','a.status','a.type','a.mobile','a.create_at')->where('status','!=',-2)->where('a.id','=',$id)->first();


        if($admin_info){
            $arr=["code"=>200,"msg"=>"获取数据成功","data"=>$admin_info];
        }else
            $arr=["code"=>0,"msg"=>"获取数据失败"];

        return $arr;

    }
    /**
     * 角色下拉菜单
     * @return array
     */
    public function roles(){

        $role_res = DB::table('admin_role')->select('id','name')->orderBy('id')->get()->toArray();
        if($role_res){
            return ['code'=>200,'msg'=>'获取数据成功','data'=>$role_res];
        }else{
            return ['code'=>1001,'msg'=>'获取数据失败'];
        }
    }
    /**获取左侧菜单列表
     * @param Request $request
     * @return array
     */
    public function menu_lists($menu_arr){

        $menu = DB::table('admin_menu')
                ->select('id','name')->where('parent_id','=',0)->where('is_show','=',1)->whereIn('id',$menu_arr)->orderBy('sort','desc')->get()->toArray();
        //得到顶级菜单
        $data =array();
        if($menu){
            foreach ($menu as $k => $row){
                //获取下级菜单和权限
                $menu_sub = DB::table('admin_menu')
                    ->select('id','name')->where('parent_id','=',$row->id)->where('is_show','=',1)->whereIn('id',$menu_arr)->orderBy('sort','desc')->get()->toArray();
                if($menu_sub)
                    $row->children=$menu_sub;
                $data[]=$row;
            }
        }

        if($data){
            return $data;
        }

    }
}

?>